package com.lamda.worker;

import com.lamda.worker.config.ApplicationSettings;
import org.izao.IZaoClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.io.*;
import java.nio.charset.Charset;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * Created by MJiao on 11/17/14.
 */
@EnableConfigurationProperties
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class ZheKouWorkerApplication {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZheKouWorkerApplication.class);

    public static void main(String[] args) {

        LOGGER.info("WorkerApplication is starting ...");

        String current = null;
        try {
            current = new java.io.File(".").getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String currentDir = System.getProperty("user.dir");

        LOGGER.info("Current dir:" + current);
        LOGGER.info("Current dir using System(user.dir):" + currentDir);

        ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(ZheKouWorkerApplication.class, args);

        String proFilePath = System.getProperty("user.dir") + "\\application.properties";
        ApplicationSettings applicationSettings = new ApplicationSettings();
        try {
            InputStream in = new BufferedInputStream(new FileInputStream(proFilePath));
            ResourceBundle resourceBundle = new PropertyResourceBundle(in);
            applicationSettings.setWorkerIp(resourceBundle.getString("worker.ip"));
            applicationSettings.setMasterIp(resourceBundle.getString("master.ip"));
            applicationSettings.setMasterSeverPort(Integer.valueOf(resourceBundle.getString("master.port")).intValue());
            String val1 =resourceBundle.getString("worker.hostname");
            String workerHostName = new String(val1.getBytes("ISO-8859-1"),"utf-8");
            applicationSettings.setWorkerHostname(workerHostName);
            val1 =resourceBundle.getString("worker.remark");
            String remark = new String(val1.getBytes("ISO-8859-1"),"utf-8");
            applicationSettings.setRemark(remark);

        }catch (Exception e){

        }

        //ApplicationSettings applicationSettings = configurableApplicationContext.getBean(ApplicationSettings.class);

        //连接Master
        IZaoClient iZaoClient = new IZaoClient(applicationSettings.getMasterIp(), applicationSettings.getMasterSeverPort());

        WorkerHolder workerHolder = configurableApplicationContext.getBean(WorkerHolder.class);
        workerHolder.setiZaoClient(iZaoClient);
        workerHolder.setApplicationSettings(applicationSettings);
        workerHolder.registerEvent();

        iZaoClient.connect();

        ZheKouWorkerApplication.printApplicationSetting(configurableApplicationContext);
    }

    /**
     * 打印应用相关配置参数
     *
     * @param configurableApplicationContext
     */
    private static void printApplicationSetting(ConfigurableApplicationContext configurableApplicationContext) {

        StringBuffer charsetInfoBuffer = new StringBuffer();
        charsetInfoBuffer.append("\n-----------System.charset------------");
        charsetInfoBuffer.append(charsetInfoBuffer.append("Default Charset=" + Charset.defaultCharset())).append("\r\n");
        charsetInfoBuffer.append("file.encoding=" + System.getProperty("file.encoding")).append("\r\n");
        charsetInfoBuffer.append("Default Charset=" + Charset.defaultCharset()).append("\r\n");
        charsetInfoBuffer.append("Default Charset in Use=" + getDefaultCharSet()).append("\r\n");
        charsetInfoBuffer.append("-------------------------------------");

        LOGGER.info(charsetInfoBuffer.toString());
//
//        ApplicationSettings applicationSettings = configurableApplicationContext.getBean(ApplicationSettings.class);
//        String applicationName = configurableApplicationContext.getApplicationName();
//
//        Field[] fields = applicationSettings.getClass().getDeclaredFields();
//
//        ASCIITableHeader[] headerObjs = {
//                new ASCIITableHeader("Key", ASCIITable.ALIGN_LEFT),
//
//                new ASCIITableHeader("Value", ASCIITable.ALIGN_LEFT),
//        };
//
//
//        for (Field f : fields) {
//            f.setAccessible(true);
//        }
//
//        String[][] data = new String[fields.length + 1][];
//        data[0] = new String[]{"applicationName", applicationName};
//
//        for (int index = 0; index < fields.length; index++) {
//            Field field = fields[index];
//            try {
//                String[] details = {field.getName(), field.get(applicationSettings).toString()};
//                data[index + 1] = details;
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        LOGGER.info(new StringBuffer("\n").append(ASCIITable.getInstance().getTable(headerObjs, data)).toString());
    }

    private static String getDefaultCharSet() {
        OutputStreamWriter writer = new OutputStreamWriter(new ByteArrayOutputStream());
        String enc = writer.getEncoding();
        return enc;
    }
}
